package org.simplecrm.repository.usergroup;

import org.simplecrm.domain.usergroup.UserGroup;
import org.slf4j.Logger;
import org.springframework.stereotype.Repository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.LinkedList;
import java.util.List;

/**
 * Implementation for MySQL database.
 */
@Repository("usergroupDAO")
public class UserGroupJdbcDAO implements UserGroupDAO {

    @org.simplecrm.misc.loginject.Logger
    private Logger LOGGER;

    @PersistenceContext(unitName = "entityManager")
    private EntityManager entityManager;

    @Override
    public List<UserGroup> getAllUsergroups() {

        List<UserGroup> userGroupList;

        Query query = entityManager.createNamedQuery("Usergroup.findAll");
        userGroupList = query.getResultList();
        if (userGroupList == null) {
            userGroupList = new LinkedList<>();
        }

        return userGroupList;
    }

    @Override
    public UserGroup getUsergroupByName(String usergroupName) {

        UserGroup userGroup;

        Query query = entityManager.createNamedQuery("Usergroup.groupByName");
        query.setParameter("groupname", usergroupName);
        userGroup = (UserGroup) query.getSingleResult();

        return userGroup;
    }
}
